/* 
 * File:   client.c
 * Author: dannv
 *
 * Created on October 19, 2009, 10:31 PM
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

#define SERV_TCP_PORT 12356
#define SIZE 1024

/*
 * Afficher l'erreur et quiter le serveur
 */
void err_stop(msg) char *msg;
{
    perror(msg);
    exit(-1);
}

/*
 * 
 */
int main(int argc, char** argv) {

    int sockfd, len, port;
    struct sockaddr_in serv_addr;
    struct hostent *host;
    char buff[SIZE];
    char msg[SIZE];

    // Prendre parametres
    if (argc < 2) {
        fprintf(stderr, "Client-Usage: %s <hostname> [port]\n", argv[0]);
        exit(1);
    }
     // prendre host et port info
    if ((host = gethostbyname(argv[1])) == NULL) {
        err_stop("Client-gethostbyname() error");
    }
    if (argc == 3) {
        sscanf(argv[2], "%d", &port);
    } else {        
        port = SERV_TCP_PORT;
    }

    // Ouvrir un sock_stream socket
    if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
        err_stop("Open socket");
    }
    
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr = *((struct in_addr *)host->h_addr);
    serv_addr.sin_port = htons(port);

    // Connect
    if (connect(sockfd, (struct sockaddr*)&serv_addr, (socklen_t)sizeof(serv_addr)) < 0) {
        err_stop("Connect to server");
    }
    // Send bonjour
    sprintf(buff, "%s\0", "Bonjour");
    if (send(sockfd, buff, strlen(buff), 0) != strlen(buff)) {
        err_stop("Send message to server");
    }
    // Recieve responses
    int i = 0;
    for (i = 0; i < 61; i++) {
        if ((len = recv(sockfd, buff, SIZE, 0)) < 0) {
            err_stop("Receive from server");
        }
        buff[len] = '\0';
        printf("Message from server : %s", buff);
    }
    shutdown(sockfd, 2);
    close(sockfd);

    return (EXIT_SUCCESS);
}

